package qjc.j_回溯;

import java.util.ArrayList;
import java.util.List;

public class j5_括号生成 {
    public List<String> generateParenthesis(int n) {
        List<String> list = new ArrayList<String>();
        backtrack(list, new StringBuilder(), 0, 0, n);
        return list;
    }

    public void backtrack(List<String> list, StringBuilder sb, int left, int right, int max) {
        if (sb.length() == max * 2) {
            list.add(sb.toString());
            return;
        }
        if (left < max) {
            sb.append('(');
            backtrack(list, sb, left + 1, right, max);
            sb.deleteCharAt(sb.length() - 1);
        }
        if (right < left) {
            sb.append(')');
            backtrack(list, sb, left, right + 1, max);
            sb.deleteCharAt(sb.length() - 1);
        }
    }
}
